import {defineStore} from "pinia";
import {IState, IActions, IShopCarItem} from "@/store/shopCarModule/types";
import zjRequest from "@/services";
import {Toast} from "vant";

const useShopCarModule = defineStore<any, IState, any, IActions>("shopCarModule", {
    state: () => ({
        shopCarList: [],
        shopCarSelectGoods: [], // 提交到选择地址页面的所有产品
        currentAddress: {
            receiverName: ""
        },
        isShowAddress: false
    }),
    actions: {
        async addShopCarAction(params) {
            const {needConfig, needParams} = params
            const res = await zjRequest.post({
                url: "/shopping/cart",
                data: needParams,
                needToken: true,
                ...needConfig
            })
            return res.code === 0
        },
        async getShopCarAction(params) {
            const {needNavigate} = params
            const res = await zjRequest.get({
                url: "/shopping/cart",
                needToken: true,
                needNavigate
            })
            if (res.code === 0) {
                return res.data
            }
        },
        async setShopCarAction(params) {
            const data = await this.getShopCarAction(params)
            if (data) {
                this.shopCarList = data.map((item: IShopCarItem) => {
                    item.checked = false
                    item.isStepperMode = false
                    return item
                })
            }
            return !!data
        },
        async updateShopCarAction(params) {
            const {needNavigate, data} = params
            const res = await zjRequest.put({
                url: "/shopping/cart",
                data,
                needToken: true,
                needNavigate
            })
            return res.code === 0
        },
        async deleteShopCarAction(params) {
            const res = await zjRequest.delete({
                url: "/shopping/manyCart",
                data: params.ids,
                needToken: true,
                needNavigate: "/shop-car"
            })
            return res.code === 0
        },
        // 点击提交后保存当前选中的商品数据
        saveShopCarDataAction(params) {
            this.shopCarSelectGoods = params
        },
        // 保存当前的地址
        setCurrentAddressAction(params) {
            this.currentAddress = params
        },
        // 判断是否出现地址页面
        setIsShowAddressAction(flag) {
            this.isShowAddress = flag
        },
        async createOrderByShoppingAction(params) {
            const res = await zjRequest.post({
                url: "/order/byShoppingCart",
                data: params.data,
                needToken: true
            })
            if (res.code === 0) {
                return res.data
            } else {
                Toast.fail(res.msg)
            }
            return false
        },
    }
})
export default useShopCarModule
